﻿using Dapper;
using Microsoft.Data.SqlClient;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using TR.Domain.Entity;
using TR.Domain.Repository.Sys_MessagesRepository;
using static Microsoft.EntityFrameworkCore.DbLoggerCategory.Database;

namespace TR.EFCore.Repository.Sys_MessagesRep
{
    public class SystemMessagesRep : ISystemMessagesRepository
    {
        private readonly MyContext myContext;
        
        public SystemMessagesRep(MyContext myContex) 
        {
            this.myContext = myContex;
        }

        //系统消息分页查询
        public async Task<FenYe<sys_Message>> SysMessageSelectFenYe(int pageSize, int currentPage, string str)
        {
            using (SqlConnection con = new SqlConnection(myContext.conStr))
            {
                DynamicParameters dynamicParameters = new DynamicParameters();
                dynamicParameters.Add("@pageSize", pageSize);
                dynamicParameters.Add("@keyName", "msg_id");
                dynamicParameters.Add("@tableName", "sys_message");
                dynamicParameters.Add("@currentPage", currentPage);
                dynamicParameters.Add("@where", str);
                dynamicParameters.Add("@rows", direction: ParameterDirection.Output, dbType: DbType.Int32);
                string sql = "exec [dbo].[procFenYe_Where] @pageSize, @keyName, @tableName, @currentPage, @where, @rows out";
                FenYe<sys_Message> fenYe = new FenYe<sys_Message>();
                fenYe.List = await con.QueryAsync<sys_Message>(sql, dynamicParameters);
                fenYe.Rows = dynamicParameters.Get<int>("rows");
                return fenYe;
            }
        }

        public async Task<bool> UpdateSysMesDel(int msg_id, string rcv_man)
        {
            // 获取当前时间
            DateTime currentTime = DateTime.Now;

            // 格式化日期为 YYYY-MM-DD
            string formattedDate = currentTime.ToString("yyyy-MM-dd");

            using (SqlConnection con = new SqlConnection(myContext.conStr))
            {
                string sql = $"Update[dbo].[sys_message] set [msg_state]= 1 and [rcv_man] = '{rcv_man}' and [rcv_time] = '{formattedDate}' where [msg_id] = '{msg_id}'";
                return con.Execute(sql) > 0 ? true : false;
            }
        }
    }
}
